package com.hybao;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class CookieUtil {
	
	/**
	 * 添加Cookie，cookie的value值只能是String
	 * @param response {@link HttpServletResponse}
	 * @param cookie_name
	 * @param cookie_str_value
	 * @param cookie_path
	 */
	public static void setCookie(HttpServletResponse response, String cookie_name,
			String cookie_str_value,String cookie_path) {
			if(cookie_str_value == null || "".equals(cookie_str_value)){
				return;
			}
			Cookie cookie = new Cookie(cookie_name, cookie_str_value);
			cookie.setPath(cookie_path);
			response.addCookie(cookie);
			response.addHeader("Set-Cookie", "HTTPOnly");
	}
	
	/**
	 * 获取存放在Cookie中的对象
	 * @param request
	 * @param cookie_name
	 * @return
	 */
	public static String getCookieValue(HttpServletRequest request, String cookie_name) {
		Cookie cookie = getCookie(request, cookie_name);
		if (cookie == null) {
			return null;
		}
		String cookieValue = cookie.getValue();
		if (cookieValue == null){
			return null;
		}
		return cookieValue;
	}
	
	private static Cookie getCookie(HttpServletRequest request, String cookie_name) {
		Cookie cookies[] = request.getCookies();
		if (cookies == null || cookie_name == null || cookie_name.length() == 0){
			return null;
		}
		Cookie cookie = null;
		for (int i = 0; i < cookies.length; i++) {
			if (!cookies[i].getName().equals(cookie_name)){
				continue;
			}
			cookie = cookies[i];
			if (request.getServerName().equals(cookie.getDomain())){
				break;
			}
		}
		return cookie;
	}
}
